# 导入的包
import os
import sys
from conf.settings import BASE_PATH
from lib import common
from lib.common import wrapper
import json
import hashlib


enter_p = 0
entercg_dic = {"name": None, "flag": False}


# 注册
def login():
    """
    注册界面
    :return:
    """
    while True:
        # 用户名字
        name = common.pass_name()
        # 用户密码
        word = common.pass_word()
        # 用户路径
        login_path = os.path.join(BASE_PATH, "db", f"{name}.json")
        # 判断用户路径是否存在
        if os.path.exists(login_path):
            print('用户名存在')
        else:
            # 加密密码准备
            md5 = hashlib.md5()
            md5.update(word.encode("utf-8"))
            # 创建用户json文件，填入信息
            with open(login_path, 'w', encoding='utf-8')as f:
                json.dump({"name": name, "pwd": md5.hexdigest(), "money": 0}, f)
            print('注册成功')
            break


# 登录
def enter():
    """
    登录界面
    :return:
    """
    # 登录次数
    for i in range(3, 0, -1):
        print(f"还剩余{i}次登录机会！")
        # 用户登录姓名
        name = common.pass_name()
        # 用户登录密码
        word = common.pass_word()
        # 组合用户路径
        enter_path = os.path.join(BASE_PATH, "db", f"{name}.json")
        # 用户密码解密准备
        md5 = hashlib.md5()
        md5.update(word.encode("utf-8"))
        # 判断用户是否存在
        if os.path.exists(enter_path):
            # 用户存在则打开用户文件
            with open(enter_path, "r", encoding="utf-8")as f1:
                # 判断密码是否相同
                if json.load(f1)["pwd"] == md5.hexdigest():
                    # 密码相等
                    entercg_dic["flag"] = True
                    entercg_dic["name"] = name
                    print("登录成功！")
                    # 把记录写入用户日志
                    common.all_log(f'{name}登录了！')
                    break
                else:
                    # 密码不相等
                    print("密码错误！")
                    # 让三次机会没有退出程序
                    if i == 1:
                        global enter_p
                        enter_p = 1
                        print("三次机会已过，自动退出程序！")
        else:
            # 用户不存在
            print("该用户没有注册！")

# 取款
@wrapper
def withdrawal():
    """
    取款界面
    :return:
    """
    print(f"{'欢迎来到取款界面'.center(30,'-')}")
    # 组合用户路径
    withdrawal_path = os.path.join(BASE_PATH, "db", f"{entercg_dic['name']}.json")
    # 打开用户文件
    with open(withdrawal_path, "r", encoding="utf-8")as f5:
        # 取出字典
        dic_withdrawal = json.load(f5)
    # 循环——有输入函数
    while True:
        # 输入取款金额
        money_withdrawal = input("请输入你想取的金额！（q或Q退出程序）：").replace(" ", "")
        # 判断取款金额是否是数字
        if money_withdrawal.isdecimal():
            # 判断用户余额是否大于取款金额
            if dic_withdrawal["money"] < int(money_withdrawal):
                print("余额不足！")
                continue
            else:
                # 用户余额足够，打开用户文件更改用户余额
                with open(withdrawal_path, "w", encoding="utf-8")as f6:
                    sum = dic_withdrawal['money']
                    sum -= int(money_withdrawal)
                    dic_withdrawal['money'] = sum
                    json.dump(dic_withdrawal, f6)
                    print(f"已取出{money_withdrawal}元！")
                    # 把记录写入用户日志文件
                    common.all_log(f'{entercg_dic["name"]}取走了{money_withdrawal}！')
                    break
        # 退出输出选择
        elif money_withdrawal.upper() == "Q":
            print("已退出取款界面！")
            break
        else:
            # 输入取款金额不符合
            print("输入错误！")

# 查询
@wrapper
def balance():
    """
    查询界面
    :return:
    """
    print(f"{'欢迎来到查询界面'.center(30, '-')}")
    # 组合用户路径
    balance_path = os.path.join(BASE_PATH, "db", f"{entercg_dic['name']}.json")
    # 打开用户文件
    with open(balance_path, "r", encoding="utf-8")as f2:
        # 查询用户余额
        print(f"余额为{json.load(f2)['money']}元！")
        # 把记录写入用户日志文件
        common.all_log(f'{entercg_dic["name"]}查询了自己的余额！')

# 充值
@wrapper
def save():
    """
    充值界面
    :return:
    """
    print(f"{'欢迎来到充值界面'.center(30, '-')}")
    # 组合用户路径
    save_path = os.path.join(BASE_PATH, "db", f"{entercg_dic['name']}.json")
    # 打开用户文件
    with open(save_path, "r", encoding="utf-8")as f3:
        # 取出用户字典
        dic_save = json.load(f3)
    # 循环
    while True:
        # 输入想充值的金额
        money_save = input("请输入你想充值的金额！（q或Q退出程序）：").replace(" ", "")
        # 判断输入是否是数字
        if money_save.isdecimal():
            # 打开用户文件
            with open(save_path, "w", encoding="utf-8")as f4:
                # 充值
                sum = dic_save['money']
                sum += int(money_save)
                dic_save['money'] = sum
                json.dump(dic_save, f4)
                print(f"已充值{money_save}")
                # 把记录写入用户日志文件
                common.all_log(f"{entercg_dic['name']}存入{money_save}元！")
                break
        # 退出程序选项
        elif money_save.upper() == "Q":
            print("已退出充值界面！")
        else:
            # 用户输入不符合
            print("输入错误！")

# 转账
@wrapper
def transfer():
    """
    转账界面
    :return:
    """
    transfer_break = 0
    print(f"{'欢迎来到转账界面'.center(30, '-')}")
    transfer_path = os.path.join(BASE_PATH, "db", f"{entercg_dic['name']}.json")   # 转账人的账号路径
    with open(transfer_path, "r", encoding="utf-8")as f7:   # 转账人的信息字典
        dic_transfer = json.load(f7)
    while True:
        transfer_name = input("情输入你想转账的账号（q或Q退出转账界面）：").replace(" ", "")
        transfer_name_path = os.path.join(BASE_PATH, "db", f"{transfer_name}.json")  # 被转账人的账号路径
        if transfer_name == entercg_dic["name"]:
            print("不可转账给自己！")
        elif os.path.exists(transfer_name_path):   # 判断转账人是否存在
            while True:
                with open(transfer_name_path, "r", encoding="utf-8")as f8:  # 被转账人的信息字典
                    dic_name_transfer = json.load(f8)
                money_transfer = input("请输入你想转账的金额（e或E退出金额界面）：").replace(" ", "")
                if money_transfer.isdecimal():
                    if dic_transfer["money"] < int(money_transfer):   # 判断转账人的余额是否足够
                        print("余额不足！")
                    else:
                        with open(transfer_path, "w", encoding="utf-8")as f9:   # 转账人扣钱
                            sum = dic_transfer['money']
                            sum -= int(money_transfer)
                            dic_transfer['money'] = sum
                            json.dump(dic_transfer, f9)
                            # 写入转账人日志文件
                            common.all_log(f'我给{transfer_name}转账了{money_transfer}元！')
                            print(f"已转出{money_transfer}元！")
                        with open(transfer_name_path, "w", encoding="utf-8")as f10:   # 被转账人加钱
                            sum = dic_name_transfer['money']
                            sum += int(money_transfer)
                            dic_name_transfer['money'] = sum
                            json.dump(dic_name_transfer, f10)
                            # 写入被转账人日志文件
                            common.transfer2(entercg_dic["name"], transfer_name, money_transfer)
                            print("转账成功，退出转账界面！")
                            transfer_break = 1
                            break
                # 退出选项
                elif money_transfer.upper() == "E":
                    break
                else:
                    # 输入不规范
                    print("输入错误！")
        # 退出选项
        elif transfer_name.upper() == "Q":
            break
        else:
            # 账号不存在
            print("没有该账号！")
        if transfer_break == 1:
            # 转账成功，退出整个程序
            break

# 流水
@wrapper
def run_water():
    """
    查询账户流水界面
    :return:
    """
    print(f"{'欢迎来到查看流水界面'.center(30, '-')}")
    # 组合用户日志文件路径
    run_water_path = os.path.join(BASE_PATH,"log",f"{entercg_dic['name']}.log")
    # 打开文件输入全部记录
    with open(run_water_path, "r", encoding="utf-8")as f11:
        print(f11.read())

# 注销
@wrapper
def logout():
    """
    注销界面
    :return:
    """
    # 改为非登录状态
    entercg_dic['flag'] = False
    print('已经注销，请重新登录！'.center(30, "-"))


# 运行序号列表
dic_log = {
    '1': enter,
    '2': login,
    '3': withdrawal,
    '4': balance,
    '5': save,
    '6': transfer,
    '7': run_water,
    '8': logout,
    '9': exit
}


# 运行程序
def run():
    """
    运行
    :return:
    """
    mgs = """
    1. 登录
    2. 注册
    3. 取钱
    4. 查看余额
    5. 存钱
    6. 转账
    7. 查看账户流水
    8. 注销
    9. 退出
    """
    print(mgs)
    while True:
        chose = input('请选择你想进入的功能序号：').replace(" ", "")
        if entercg_dic['flag'] == True:
            if chose == '1':
                print("已登录成功，无法注册！")
            elif chose == '2':
                print("已登录成功，无法继续登录！")
            elif chose == '3' or chose == '4' or chose == '5' or chose == '6' or chose == '7' or chose == '8':
                dic_log[chose]()
                if enter_p == 1:
                    break
            elif chose == '9':
                print('退出程序')
                break
            else:
                print('输出错误')
        else:
            if chose == '1' or chose == '2' or chose == '3' or chose == '4' or chose == '5' or chose == '6' or chose == '7' or chose == '8':
                dic_log[chose]()
                if enter_p == 1:
                    break
            elif chose == '9':
                print('退出程序')
                break
            else:
                print('输出错误')












